import importlib
from regs import register_players

class GamePlatform:
    def __init__(self):
        self.participants = {}  # 参赛者字典，保存参赛者名称和其对应的程序模块
        self.scores = {}  # 参赛者积分字典，保存参赛者名称和其对应的积分
    
    def register_participant(self, name, module_name):
        try:
            module = importlib.import_module(module_name)
            self.participants[name] = module
            self.scores[name] = 0
            print(f"{name}的程序已注册成功！")
        except ImportError:
            print(f"找不到名为{module_name}的程序模块！注册失败。")

    def play_game(self, player1, player2):
        # 根据参赛者的程序模块进行对战，根据规则判断获胜者，并更新积分
        move1 = self.participants[player1].make_move()
        move2 = self.participants[player2].make_move()

        if move1 > move2:
            self.scores[player1] += 1
            self.scores[player2] -= 1
            print(f"{player1}获胜！")
        elif move2 > move1:
            self.scores[player2] += 1
            self.scores[player1] -= 1
            print(f"{player2}获胜！")
        else:
            print("平局！")

        print(f"{move1} vs {move2}")
        print(f"当前积分：{player1}: {self.scores[player1]} 分, {player2}: {self.scores[player2]} 分")
        print()

    def run_tournament(self):
        participants = list(self.participants.keys())

        for i in range(len(participants)):
            for j in range(i+1, len(participants)):
                print(f"正在进行 {participants[i]} VS {participants[j]} 的对战...")

                for _ in range(6):  # 进行6盘对弈
                    self.play_game(participants[i], participants[j])

        print("循环赛结束！")
        self.update_ranking()

    def update_ranking(self):
        ranking = sorted(self.scores.items(), key=lambda x: x[1], reverse=True)

        print("排行榜：")
        for i, (participant, score) in enumerate(ranking):
            print(f"{i+1}. {participant}: {score} 分")

    def show_leaderboard(self):
        ranking = sorted(self.scores.items(), key=lambda x: x[1], reverse=True)

        print("排行榜：")
        for i, (participant, score) in enumerate(ranking):
            print(f"{i+1}. {participant}: {score} 分")

def main():
    platform = GamePlatform()

    register_players(platform)  # 调用注册函数

    platform.run_tournament()
    platform.show_leaderboard()

if __name__ == "__main__":
    main()
